package demo;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Random;

/**
 * @author yuyufeng
 * @date 2017/10/30
 */
public class HandlerAndIndex {
    public static void main(String[] args) throws IOException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        RestClient restClient = RestClient.builder(
                new HttpHost("127.0.0.1", 9200, "http")).build();
        Response response = null;


        String file = "H://profler.log";
        BufferedReader bf = new BufferedReader(new FileReader(file));
        String str = null;
        while ((str = bf.readLine()) != null) {
            if (str.indexOf("distributorCode") != -1) {
                try {
                    String distributorCode = str.substring(str.indexOf("distributorCode") + 16, str.indexOf("]", str.indexOf("distributorCode")));
                    String url = str.substring(str.indexOf("http://"), str.indexOf(".htm") + 4);
                    String sign = str.substring(str.indexOf("sign=") + 5, str.indexOf("]", str.indexOf("sign=")));
                    String data = str.substring(str.indexOf("data=") + 5, str.lastIndexOf("]"));
                    String json = "{" +
                            "\"requestDateTime\":\"" + dateFormat.format(new Date())+
                            "\",\"distributorCode\":\"" + distributorCode +
                            "\",\"url\":\"" + url +
                            "\",\"sign\":\"" + sign +
                            "\",\"data\":" + data +
                            "}";
                    System.out.println(json);
                    HttpEntity entity = new StringEntity(json, "utf-8");
                    Header header = new BasicHeader("referer", "http://www.bababus.com");
                    response = restClient.performRequest("POST", "/distributor/request", Collections.emptyMap(), entity, header);
                    System.out.println(EntityUtils.toString(response.getEntity()));
                } catch (Exception e) {
                    System.out.println("eror " + str + " " + e.getMessage());
                    e.printStackTrace();
                }

            }
         /*   try {
                Thread.sleep(new Random().nextInt(500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
        }
        restClient.close();
    }
}
